package day03;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import org.junit.Test;
import utils.DruidUtils;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.Properties;

public class DruidDemo {
    public static void main(String[] args) {
        Properties pro = new Properties();
        try {
            //方式一：同包下，配置文件直接加载
            //pro.load(DruidDemo.class.getResourceAsStream("druid.properties"));
            //方式二：src下，使用类加载器getClassLoader
            pro.load(DruidDemo.class.getClassLoader().getResourceAsStream("druid.properties"));

            //获取数据库连接
            DataSource ds = DruidDataSourceFactory.createDataSource(pro);
            Connection con = ds.getConnection();
            System.out.println(con);
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }
    @Test //使用工具类创建Druid连接池
    public void test(){
        Connection con = DruidUtils.getConnection();
        PreparedStatement ps = null;
        System.out.println(con);
        String sql = "insert into demo values (null,?,?)";
        try {
            ps = con.prepareStatement(sql);
            ps.setString(1,"teimis");
            ps.setString(2,"Niddhog");
            ps.executeUpdate();
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            DruidUtils.close(con,ps);
        }
    }
}
